﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace Mercator2
{
    public partial class DeviceMap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                string latitudeStr = "";
                string longitudeStr = "";

                // Coloca mapa e alfinete na pagina com posicionamento do servidor.

                if ((Request.QueryString != null) && (Request.QueryString.Count > 0))
                {
                    latitudeStr = Request.QueryString["latitude"].ToString();
                    longitudeStr = Request.QueryString["longitude"].ToString();
                    BuildScript(latitudeStr, longitudeStr);
                }
                else
                {
                    //-40,288615	-20,3558483333333
                    latitudeStr = "-20.3558483333333";// Request.QueryString["latitude"].ToString();
                    longitudeStr = "-40.288615";// Request.QueryString["longitude"].ToString();
                    BuildScript(latitudeStr, longitudeStr);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }

            //}

        }

        private void setTextAddress(string longitude, string latitude)
        {

            // http://stackoverflow.com/questions/3151450/google-geolocation-api-use-longitude-and-latitude-to-get-address

            // 	-40.402864	-20.342288	0.0	0.0	BR-262 - Pistal Lateral - Vila Capixaba, Cariacica - ES, Brazil
            // -40.288124	-20.355536	0.0	0.0	R. Natal, 1-61 - Praia de Itapoã, Vila Velha - ES, 29101-710, Brazil
            // http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding
            //http://maps.google.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

            try
            {
                //string longitude = "40.714224"; string latitude = "-73.961452";
                //string longitude = "-40.288124"; string latitude = "-20.355536";
                string Address_ShortName = "";
                string Address_country = "";
                string Address_administrative_area_level_1 = "";
                string Address_administrative_area_level_2 = "";
                string Address_administrative_area_level_3 = "";
                string Address_colloquial_area = "";
                string Address_locality = "";
                string Address_sublocality = "";
                string Address_neighborhood = "";
                string Street_address = "";

                ReverseGeoLookup.ReverseGeoLookup.ReverseGeoLoc(longitude, latitude,
                    out Address_ShortName,
                    out Address_country,
                    out Address_administrative_area_level_1,
                    out Address_administrative_area_level_2,
                    out Address_administrative_area_level_3,
                    out Address_colloquial_area,
                    out Address_locality,
                    out Address_sublocality,
                    out Address_neighborhood,
                    out Street_address);

                //Console.WriteLine(
                //    "Street_address=" + Street_address + "\n" + 
                //    "Address_ShortName=" + Address_ShortName + " - " +
                //    "Address_country=" + Address_country + " - " +
                //    "Address_administrative_area_level_1=" + Address_administrative_area_level_1 + " - " +
                //    "Address_administrative_area_level_2=" + Address_administrative_area_level_2 + " - " +
                //    "Address_administrative_area_level_3=" + Address_administrative_area_level_3 + " - " +
                //    "Address_colloquial_area=" + Address_colloquial_area + " -  " +
                //    "Address_locality=" + Address_locality + " - " +
                //    "Address_sublocality=" + Address_sublocality + " - " +
                //    "Address_neighborhood=" + Address_neighborhood);

                txtAddress.Text =
                    "Street_address=" + Street_address + "\n" +
                    "Address_ShortName=" + Address_ShortName + "\n" +
                    "Address_country=" + Address_country + "\n" +
                    "Address_administrative_area_level_1=" + Address_administrative_area_level_1 + "\n" +
                    "Address_administrative_area_level_2=" + Address_administrative_area_level_2 + "\n" +
                    "Address_administrative_area_level_3=" + Address_administrative_area_level_3 + "\n" +
                    "Address_colloquial_area=" + Address_colloquial_area + " -  " +
                    "Address_locality=" + Address_locality + "\n" +
                    "Address_sublocality=" + Address_sublocality + "\n" +
                    "Address_neighborhood=" + Address_neighborhood;

                //Console.In.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }
        }

        private string BuildScript(string Latitude, string Longitude)
        {
            String Locations = "";

            Latitude = Latitude.Replace(",", ".");
            Longitude = Longitude.Replace(",", ".");

            // create a line of JavaScript for marker on map for this record	
            Locations = Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")));";
            //}

            // construct the final script
            //alert(window.location.host);
            js.Text = @"<script type='text/javascript'>
                            function initialize() {
                              if (GBrowserIsCompatible()) {

                                var map = new GMap2(document.getElementById('map_canvas'));
                                map.setCenter(new GLatLng(" + Latitude + "," + Longitude + @"),15); 
                                " + Locations + @"
                                map.setUIToDefault();
                              }
                            }
                            </script> ";

            setTextAddress(Longitude, Latitude);

            return Locations;
        }

        public System.Data.DataSet getData(string connectionString, string currentTableName, string whereClause)
        {
            System.Data.DataSet tempDataSet = new System.Data.DataSet();
            SqlDataAdapter currentDataAdapter = null;

            try
            {
                SqlConnection dataConnection = new SqlConnection(connectionString);

                //OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder();//(OleDbDataAdapter)currentDataAdapter);
                //cmdBuilder.GetInsertCommand();

                string SQL = "SELECT * FROM " + currentTableName;
                if ((whereClause != null) && (whereClause.Trim() != ""))
                    SQL += " WHERE " + whereClause;

                SqlCommand tableCommand = new SqlCommand(SQL, dataConnection);

                currentDataAdapter = new SqlDataAdapter(tableCommand);

                currentDataAdapter.Fill(tempDataSet);
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }

            return tempDataSet;
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //' Retrieve the company name from the appropriate cell.
            //Dim companyName As String = CustomersGridView.SelectedRow.Cells(2).Text
            string latitudeStr = GridView1.SelectedRow.Cells[6].Text;
            string longitudeStr = GridView1.SelectedRow.Cells[5].Text;

            //' Display company name selected by the user.
            //Message.Text = "You selected " & companyName & "."

            //http://localhost:48507/TrackingMap.aspx?latitude=-20.3550483333333&longitude=-40.28837
            //./TrackingMap.aspx?latitude=-40.28837&longitude=-20.3550483333333
            //./TrackingMap.aspx?latitude=-40.28822&longitude=-20.3552333333333
            //Response.Redirect("./map.aspx?latitude=" + latitudeStr.Replace(",",".") + "&" + "longitude=" + longitudeStr.Replace(",","."));
            Response.Redirect("./TrackingMap.aspx?latitude=" + latitudeStr.Replace(",", ".") + "&" + "longitude=" + longitudeStr.Replace(",", "."));

            // http://localhost:58159/MERCATOR_Portal/Forms/Veiculo/Edit.aspx?VeiculoID=6044
            // http://localhost:58159/MERCATOR_Portal/Forms/Veiculo/List.aspx
            //http://www.lifeware.com.br/Mercatorportal/Forms/Veiculo/List.aspx

            //Device.aspx?field={0}

        }

        protected void GridView1_SelectedIndexChanged2(object sender, EventArgs e)
        {
            //' Retrieve the company name from the appropriate cell.
            //Dim companyName As String = CustomersGridView.SelectedRow.Cells(2).Text
            string latitudeStr = GridView1.SelectedRow.Cells[6].Text;
            string longitudeStr = GridView1.SelectedRow.Cells[5].Text;

            //' Display company name selected by the user.
            //Message.Text = "You selected " & companyName & "."

            //./TrackingMap.aspx?latitude=-40.28837&longitude=-20.3550483333333
            //./TrackingMap.aspx?latitude=-40.28822&longitude=-20.3552333333333
            //Response.Redirect("./TrackingMap.aspx?latitude=" + latitudeStr.Replace(",", ".") + "&" + "longitude=" + longitudeStr.Replace(",", "."));
            BuildScript(latitudeStr, longitudeStr);

            // http://localhost:58159/MERCATOR_Portal/Forms/Veiculo/Edit.aspx?VeiculoID=6044
            // http://localhost:58159/MERCATOR_Portal/Forms/Veiculo/List.aspx
            //http://www.lifeware.com.br/Mercatorportal/Forms/Veiculo/List.aspx

            //Device.aspx?field={0}

        }
    }
}